package com.ruoyi.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import java.io.InputStream;
import java.util.UUID;


public class OSSUtils {
    private static String endpoint = "oss-cn-beijing.aliyuncs.com";
    private static String accessKeyId = "LTAI5tEzSzVTq6yRgY1yX17M";
    private static String accessKeySecret = "et9BmchV9LG1nYg5yp2nDOADBMwJsg";
    private static String bucketName = "gzq123";
    // 基础路径，不包含动态文件名
    private static String basePath = "upload/";

    public static String upload(String fileName, InputStream inputStream) {
        // 生成UUID（去除横线，避免URL特殊字符问题）
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        // 分离文件名和扩展名（如"image.png" → 文件名"image"，扩展名".png"）
        int lastDotIndex = fileName.lastIndexOf(".");
        String name = lastDotIndex > 0 ? fileName.substring(0, lastDotIndex) : fileName;
        String ext = lastDotIndex > 0 ? fileName.substring(lastDotIndex) : "";

        // 拼接唯一文件名：UUID_原文件名.扩展名
        String uniqueFileName = uuid + "_" + name + ext;

        // 完整OSS存储路径：基础路径 + 唯一文件名
        String objectName = basePath + uniqueFileName;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName, objectName, inputStream);
            return objectName; // 返回包含UUID的唯一路径
        } finally {
            ossClient.shutdown();
        }
    }
}